<template>
  <el-dialog
    v-model="visible"
    title="审核告警"
    width="700px"
    :close-on-click-modal="false"
  >
    <el-form
      ref="reviewFormRef"
      :model="reviewForm"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="告警ID">
        <span class="alert-id">{{ alert.alert_id }}</span>
      </el-form-item>

      <el-form-item label="资产信息">
        <span>{{ alert.asset_ip }}:{{ alert.asset_port || "-" }}</span>
      </el-form-item>

      <el-form-item label="审核决策" prop="decision">
        <el-radio-group
          v-model="reviewForm.decision"
          @change="handleDecisionChange"
        >
          <el-radio label="confirmed"> 确认告警 </el-radio>
          <el-radio label="false_positive"> 误报 </el-radio>
          <el-radio label="ignored"> 忽略 </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 快捷加白选项 -->
      <el-form-item
        v-if="
          reviewForm.decision === 'false_positive' ||
          reviewForm.decision === 'ignored'
        "
      >
        <el-checkbox v-model="reviewForm.add_to_whitelist">
          同时加入白名单
        </el-checkbox>
        <div class="form-hint">勾选后下方显示快捷加白选项</div>
      </el-form-item>

      <!-- 加白配置 -->
      <div
        v-if="reviewForm.add_to_whitelist"
        class="whitelist-config"
        style="
          padding: 15px;
          background-color: #f5f7fa;
          border-radius: 4px;
          margin-bottom: 15px;
        "
      >
        <el-form-item label="加白类型" prop="whitelist_type">
          <el-select
            v-model="reviewForm.whitelist_type"
            placeholder="请选择加白类型"
            style="width: 100%"
          >
            <el-option label="IP地址加白" value="ip" />
            <el-option label="IP段加白" value="ip_range" />
            <el-option label="端口加白" value="port" />
            <el-option label="IP+端口加白" value="ip_port" />
          </el-select>
        </el-form-item>

        <el-form-item label="匹配条件" prop="whitelist_condition">
          <el-input
            v-model="reviewForm.whitelist_condition"
            :placeholder="getWhitelistPlaceholder()"
            style="width: 100%"
          />
          <div class="form-hint">自动填充，可手动修改</div>
        </el-form-item>

        <el-form-item label="适用场景">
          <el-checkbox-group v-model="reviewForm.whitelist_scenes">
            <el-checkbox label="current">当前场景</el-checkbox>
            <el-checkbox label="all">所有场景</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="规则名称" prop="whitelist_rule_name">
          <el-input
            v-model="reviewForm.whitelist_rule_name"
            placeholder="自动生成或手动输入"
            style="width: 100%"
          />
        </el-form-item>
      </div>

      <el-form-item label="审核意见" prop="comment">
        <el-input
          v-model="reviewForm.comment"
          type="textarea"
          :rows="4"
          placeholder="请输入审核意见（选填，最多500字）"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        提交审核
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from "vue";
import { ElMessage, ElMessageBox, ElForm, ElIcon } from "element-plus";
import {
  CircleCheck,
  CircleClose,
  RemoveFilled,
} from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";
import { reviewAlert } from "../../../servers";

// 定义props
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  alert: {
    type: Object,
    default: () => ({}),
  },
});

// 定义emits
const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "reviewed"): void;
}>();

// visible computed 属性
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

const reviewFormRef = ref<FormInstance>();
const submitting = ref(false);

// 审核表单
const reviewForm = reactive({
  decision: "confirmed" as "confirmed" | "false_positive" | "ignored",
  comment: "",
  add_to_whitelist: false,
  whitelist_type: "ip",
  whitelist_condition: "",
  whitelist_scenes: ["current"] as string[],
  whitelist_rule_name: "",
});

// 表单规则
const formRules = {
  decision: [{ required: true, message: "请选择审核决策", trigger: "change" }],
  whitelist_type: [
    {
      required: true,
      message: "请选择加白类型",
      trigger: "change",
      validator: (rule: any, value: any, callback: any) => {
        if (reviewForm.add_to_whitelist && !value) {
          callback(new Error("请选择加白类型"));
        } else {
          callback();
        }
      },
    },
  ],
  whitelist_condition: [
    {
      required: true,
      message: "请输入匹配条件",
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (reviewForm.add_to_whitelist && !value) {
          callback(new Error("请输入匹配条件"));
        } else {
          callback();
        }
      },
    },
  ],
  whitelist_rule_name: [
    {
      required: true,
      message: "请输入规则名称",
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (reviewForm.add_to_whitelist && !value) {
          callback(new Error("请输入规则名称"));
        } else {
          callback();
        }
      },
    },
  ],
};

// 监听告警变化，自动填充加白条件
watch(
  () => props.alert,
  (newAlert) => {
    if (newAlert && newAlert.alert_id) {
      // 自动生成规则名称
      const date = new Date().toISOString().split("T")[0].replace(/-/g, "");
      reviewForm.whitelist_rule_name = `IP加白-${newAlert.asset_ip}-${date}`;

      // 自动填充匹配条件
      if (newAlert.asset_ip) {
        reviewForm.whitelist_condition = newAlert.asset_ip;
      }
    }
  },
  { immediate: true }
);

// 监听决策变化，重置加白选项
watch(
  () => reviewForm.decision,
  (newDecision) => {
    if (newDecision !== "false_positive" && newDecision !== "ignored") {
      reviewForm.add_to_whitelist = false;
    }
  }
);

// 监听加白类型变化，更新匹配条件
watch(
  () => reviewForm.whitelist_type,
  (newType) => {
    if (props.alert && props.alert.asset_ip) {
      if (newType === "ip") {
        reviewForm.whitelist_condition = props.alert.asset_ip;
      } else if (newType === "ip_port" && props.alert.asset_port) {
        reviewForm.whitelist_condition = `${props.alert.asset_ip}:${props.alert.asset_port}`;
      } else if (newType === "port" && props.alert.asset_port) {
        reviewForm.whitelist_condition = props.alert.asset_port;
      }
    }
  }
);

// 获取加白类型占位符
const getWhitelistPlaceholder = (): string => {
  const placeholders: Record<string, string> = {
    ip: "如: 192.168.1.100",
    ip_range: "如: 192.168.1.0/24",
    port: "如: 80, 443",
    ip_port: "如: 192.168.1.100:443",
  };
  return placeholders[reviewForm.whitelist_type] || "请输入匹配条件";
};

// 决策变化处理
const handleDecisionChange = () => {
  reviewForm.add_to_whitelist = false;
};

// 提交审核
const handleSubmit = async () => {
  if (!reviewFormRef.value) return;

  try {
    await reviewFormRef.value.validate();
  } catch (error) {
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要${getDecisionText(reviewForm.decision)}此告警吗？`,
      "确认审核",
      {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }
    );

    submitting.value = true;

    const requestData: any = {
      alert_id: props.alert.alert_id,
      review_decision: reviewForm.decision,
      review_comment: reviewForm.comment || undefined,
    };

    // 如果勾选了加入白名单
    if (reviewForm.add_to_whitelist) {
      requestData.add_to_whitelist = true;

      // 处理适用场景
      let applicableDimensions = "";
      if (reviewForm.whitelist_scenes.includes("all")) {
        // 如果选择了"所有场景"，不需要设置 applicable_dimensions（后端会处理）
        applicableDimensions = "";
      } else if (reviewForm.whitelist_scenes.includes("current")) {
        // 映射当前场景类型到维度
        const sceneDimensionMap: Record<string, string> = {
          unreported_asset: "unreported_asset",
          high_risk_asset: "high_risk_asset",
          vulnerability_scan: "vuln_scan",
          vulnerability_confirmed: "vuln_scan",
          threat_intelligence_hit: "intel_hit",
          local_remote_diff: "unreported_asset",
        };
        const dimension =
          sceneDimensionMap[props.alert.scene_type] || props.alert.scene_type;
        applicableDimensions = dimension;
      }

      requestData.whitelist_config = {
        rule_name: reviewForm.whitelist_rule_name,
        rule_type: reviewForm.whitelist_type,
        rule_description: `从告警审核快捷加白 - ${props.alert.alert_id}`,
        match_condition: reviewForm.whitelist_condition,
        applicable_dimensions: applicableDimensions,
        is_enabled: true,
      };
    }

    const result = await reviewAlert(requestData);

    // 处理审核结果
    let message = result?.message || "审核成功";

    // 处理工单创建结果
    if (result?.data?.ticket_result) {
      const {
        action,
        ticket_id,
        message: ticketMsg,
      } = result.data.ticket_result;
      if (action === "created") {
        message = `审核成功！已创建工单 TK-${ticket_id}`;
      } else if (action === "aggregated") {
        message = `审核成功！已添加到工单 TK-${ticket_id}`;
      } else if (action === "skipped") {
        message = `审核成功！告警已关联工单 TK-${ticket_id}`;
      } else if (ticketMsg) {
        message = ticketMsg;
      }
    }

    // 处理白名单创建结果
    if (result?.data?.whitelist_result) {
      const { success, message: whitelistMsg } = result.data.whitelist_result;
      if (success) {
        message += `，${whitelistMsg}`;
      } else {
        message += `，但${whitelistMsg}`;
      }
    }

    ElMessage.success(message);
    emit("reviewed");
    visible.value = false;
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "审核失败");
    }
  } finally {
    submitting.value = false;
  }
};

// 获取决策文本
const getDecisionText = (
  decision: "confirmed" | "false_positive" | "ignored"
): string => {
  const map: Record<string, string> = {
    confirmed: "确认",
    false_positive: "标记为误报",
    ignored: "忽略",
  };
  return map[decision] || "";
};

// 取消
const handleCancel = () => {
  visible.value = false;
};
</script>

<style scoped lang="scss">
.alert-id {
  font-weight: 500;
  color: #333;
}

.form-hint {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.whitelist-config {
  .el-form-item {
    margin-bottom: 15px;
  }
}
</style>
